package com.microservices.yucloud.appweb.utils;

import com.microservices.yucloud.appweb.enums.BizOrderEventsEnum;
import com.microservices.yucloud.appweb.enums.BizOrderStatusEnum;
import org.springframework.messaging.Message;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.state.State;
import org.springframework.statemachine.support.StateMachineUtils;
import org.springframework.statemachine.transition.Transition;
import org.springframework.statemachine.trigger.DefaultTriggerContext;
import org.springframework.statemachine.trigger.Trigger;

/**
 * @author zy
 * @date 2019-09-04 19:47
 **/
public class BizOrderStateMachineUtils {
    /**
     * 判断是否可以执行对应的event
     *
     * @param stateMachine
     * @param eventMsg
     * @return
     */
    public static boolean acceptEvent(StateMachine<BizOrderStatusEnum, BizOrderEventsEnum> stateMachine, Message<BizOrderEventsEnum> eventMsg) {
        State<BizOrderStatusEnum, BizOrderEventsEnum> state = stateMachine.getState();

        for (Transition<BizOrderStatusEnum, BizOrderEventsEnum> transition : stateMachine.getTransitions()) {

            State<BizOrderStatusEnum, BizOrderEventsEnum> source = transition.getSource();
            Trigger<BizOrderStatusEnum, BizOrderEventsEnum> trigger = transition.getTrigger();

            if (state != null && StateMachineUtils.containsAtleastOne(source.getIds(), state.getIds())) {
                if (trigger != null && trigger.evaluate(new DefaultTriggerContext<>(eventMsg.getPayload()))) {
                    return true;
                }
            }
        }
        return false;
    }
}
